{
 "cells": [
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 1.1.4 多进程、多线程同步（通讯）的方法 ⭐⭐⭐⭐⭐\n",
    "\n",
    "## 进程间通信（IPC, Inter-Process Communication）\n",
    "由于**进程间不共享内存**，需要特殊的通信机制：\n",
    "\n",
    "1. **管道（Pipe）**：\n",
    "   - 适用于**父子进程通信**，数据单向传输，如 `os.pipe()`\n",
    "\n",
    "2. **消息队列（Message Queue）**：\n",
    "   - 使用 `multiprocessing.Queue` 进行进程间消息传递\n",
    "\n",
    "3. **共享内存（Shared Memory）**：\n",
    "   - `multiprocessing.Value` 或 `multiprocessing.Array` 共享数据\n",
    "\n",
    "4. **信号（Signal）**：\n",
    "   - 进程间通过 `signal` 机制传递信息\n",
    "\n",
    "5. **套接字（Socket）**：\n",
    "   - 适用于**网络通信**或**跨机器进程通信**\n",
    "\n",
    "---\n",
    "\n",
    "## 线程同步方法\n",
    "**线程共享内存**，必须**同步访问**：\n",
    "\n",
    "1. **互斥锁（Mutex）**：\n",
    "   - `threading.Lock()`，确保同一时间只有一个线程访问共享资源\n",
    "\n",
    "2. **信号量（Semaphore）**：\n",
    "   - `threading.Semaphore(value)` 控制多个线程对资源的访问\n",
    "\n",
    "3. **事件（Event）**：\n",
    "   - `threading.Event()` 让线程等待某个事件发生\n",
    "\n",
    "4. **条件变量（Condition）**：\n",
    "   - `threading.Condition()` 线程间的协调机制\n"
   ],
   "id": "9556f283f86d0f3b"
  },
  {
   "metadata": {},
   "cell_type": "raw",
   "source": "举例：管道（Pipe）",
   "id": "439f3eb146cb5a23"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-03-04T07:29:50.860327900Z",
     "start_time": "2025-03-04T07:28:17.896873Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 导入Pipe函数，用于创建一个管道来实现进程间的通信\n",
    "from multiprocessing import Pipe\n",
    "\n",
    "# 创建管道，Pipe()函数返回一对连接对象\n",
    "# parent_conn 用于父进程端，child_conn 用于子进程端\n",
    "parent_conn, child_conn = Pipe()\n",
    "\n",
    "# 定义子进程要执行的函数\n",
    "def child_process(conn):\n",
    "    # 通过管道发送一条字符串消息到连接的另一端（父进程）\n",
    "    conn.send(\"Hello from child process!\")\n",
    "    # 发送完毕后，关闭管道连接，释放资源\n",
    "    conn.close()\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    # 导入Process类，用于创建新的进程\n",
    "    from multiprocessing import Process\n",
    "    # 创建一个新的进程对象，目标函数为child_process，并传入child_conn作为参数\n",
    "    p = Process(target=child_process, args=(child_conn,))\n",
    "    # 启动子进程，子进程开始执行child_process函数\n",
    "    p.start()\n",
    "\n",
    "    # 在父进程中，通过parent_conn从管道中接收子进程发送的数据\n",
    "    print(parent_conn.recv())  # 输出子进程发送的消息\n",
    "\n",
    "    # 等待子进程结束，确保子进程执行完毕后再继续执行后续代码\n",
    "    p.join()\n"
   ],
   "id": "fe94b7de75be5849",
   "outputs": [],
   "execution_count": null
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
